package org.kjtc.service;

import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.kjtc.entity.WxUserEntity;
import org.kjtc.weChatUtil.JsonUtils;
import org.kjtc.weChatUtil.StringUtils;
import org.kjtc.weChatUtil.WXUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author: xiaojinlu1990@ 163.com
 * @Date: 2019/3/19 0019.
 * @Version 1.0
 */
@Service
public class WxUserService {

    @Resource
    private WXUtils wxUtils;


    private static Logger logger = Logger.getLogger(WxUserService.class);
    public Map setUserInfo(HttpServletRequest request, ModelMap map) {
        // 跳转页面标识参数128k
        String state = request.getParameter("state");
        // 通过code获取access_token
        String code = request.getParameter("code");
        logger.info("authorize:code:{}"+ code);

        // 获取access_token和openid
        com.alibaba.fastjson.JSONObject jsonToken = wxUtils.getJsapiAccessTokenByCode(code);

        //获取用户信息
        // 通过access_token和openid请求获取用户信息
        com.alibaba.fastjson.JSONObject jsonUserinfo = wxUtils.getJsapiUserinfo(jsonToken.getString("access_token"), jsonToken.getString("openid"));
        Map<String,Object> userMap = new HashedMap();
        for(String str:jsonUserinfo.keySet()){
            System.out.println(str + ":" +jsonUserinfo.get(str));
            switch(str){
                case "country":
                    userMap.put(str,StringUtils.getEncodeCode(jsonUserinfo,str));
                    break;
                case "province":
                    userMap.put(str,StringUtils.getEncodeCode(jsonUserinfo,str));
                    break;
                case "city":
                    userMap.put(str,StringUtils.getEncodeCode(jsonUserinfo,str));
                    break;
                case "nickname":
                    userMap.put(str,StringUtils.getEncodeCode(jsonUserinfo,str));
                    break;
                default:
                    userMap.put(str,jsonUserinfo.get(str));
                    break;
            }
        }
        //map转实体
        WxUserEntity wxUserEntity = (WxUserEntity) JsonUtils.map2Object(userMap, WxUserEntity.class);
        System.out.println(wxUserEntity.toString());


        return map;
    }
}
